package Controller

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"gopkg.in/ini.v1"
	"log"
	"net/http"
	"time"
	"web_back_go/DAO/gorm/GormModel"
	"web_back_go/Dto"
)

func TestController(c *gin.Context) {
	// 直接初始化 order
	shopID := uint64(123)
	actualTotal := float64(200.50)
	payType := 1
	remarks := "这是一个订单备注"
	dvyType := "快递"
	dvyID := uint64(456)
	productNums := 5
	isPayed := 0
	orderType := int8(2)
	closeType := int8(1)
	reduceAmount := float64(10.00)

	// 初始化 order 变量
	order := GormModel.TzOrder{
		ShopID:        &shopID,
		ProdName:      "商品1",
		UserID:        "user123",
		OrderNumber:   "20250216001",
		Total:         210.50,
		ActualTotal:   &actualTotal,
		PayType:       &payType,
		Remarks:       &remarks,
		Status:        0,
		DvyType:       &dvyType,
		DvyID:         &dvyID,
		DvyFlowID:     "123456789",
		FreightAmount: 10.00,
		AddrOrderID:   &shopID,
		ProductNums:   &productNums,
		CreateTime:    time.Now(),
		IsPayed:       &isPayed,
		DeleteStatus:  0,
		RefundSts:     0,
		ReduceAmount:  &reduceAmount,
		OrderType:     &orderType,
		CloseType:     &closeType,
		ShopName:      "示例店铺",
	}

	var order1 Dto.OrderAsset
	// 带参数的拷贝
	err := copier.CopyWithOption(&order1, &order, copier.Option{IgnoreEmpty: true, DeepCopy: true})
	if err != nil {
		log.Println("拷贝失败", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "拷贝订单数据失败: " + err.Error()})
		return
	}

	// 正确比较指针指向的值
	tmp := 1
	if order.IsPayed != nil && *order.IsPayed == tmp {
		order1.IsPayed = true
	} else {
		order1.IsPayed = false
	}

	// 加载配置文件
	cfg, err := ini.Load("./Config/config.ini")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "加载配置文件失败: " + err.Error()})
		return
	}

	// 序列化订单数据
	jsonData, err := json.Marshal(order1)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "序列化订单数据失败: " + err.Error()})
		return
	}

	log.Println("发送数据", string(jsonData))
	url := cfg.Section("blockchain").Key("url").String() + "/UpdateAsset"
	log.Println("发送地址", url)

	// 创建 PUT 请求
	req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonData))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建请求失败: " + err.Error()})
		return
	}
	// 设置请求头
	req.Header.Set("Content-Type", "application/json")

	// 执行请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "发送请求失败: " + err.Error()})
		return
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("请求失败，状态码: %d", resp.StatusCode)})
		return
	}

	// 解析响应数据
	var response map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&response)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "解析响应数据失败: " + err.Error()})
		return
	}

	// 返回响应数据
	c.JSON(http.StatusOK, response)
}
